package com.zj.system.config;

import com.zj.system.shiro.MyRealm;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;


import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @program: clms-seventh
 * @description: realm的配置类
 * @author: 张静
 * @create: 2021-07-16 20:21
 **/
@Configuration
public class RealmConfig {
    //1.spring容器创建SecurityManager对象
    @Bean
    public DefaultWebSecurityManager securityManager(){
        //创建一个SecurityManager对象
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        securityManager.setRealm(realm());//自定义realm对象
        return securityManager;
    }

    //自定义realm
    @Bean
    public Realm realm(){
        MyRealm myRealm=new MyRealm();
        myRealm.setCredentialsMatcher(credentialsMatcher());//设置密码匹配器
        return myRealm;
    }
    //创建一个密码匹配器
    @Bean
    public CredentialsMatcher credentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("MD5");//指定加密方式  MD5
        credentialsMatcher.setHashIterations(1024);//加密的次数 1024
        return credentialsMatcher;
    }
    //shiro的过滤器涟
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager());
        //放行的资源
        Map<String,String> map=new LinkedHashMap<>();
        map.put("/system/login","anon");
        map.put("/**","anon");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;

    }

//    注入过滤器组件
//    @Bean
//    public FilterRegistrationBean<Filter> filter(){
//        FilterRegistrationBean<Filter> registrationBean=new FilterRegistrationBean<>();
//        registrationBean.setFilter(new DelegatingFilterProxy());
//        registrationBean.setName("shiroFilter");
//        registrationBean.addUrlPatterns("/*");
//        return registrationBean;
//    }
    @Bean
    public FilterRegistrationBean<Filter> filterFilterRegistrationBean(){
                FilterRegistrationBean<Filter> registrationBean=new FilterRegistrationBean<>();
        registrationBean.setFilter(new DelegatingFilterProxy());
        registrationBean.setName("shiroFilter");
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }
}
